<template>
  <card>
    <template slot="header">
      <h3 class="title">评测方案</h3>
    </template>

    <div class="row">
      <div class="col-md-4 px-md-1 text-left">
        <base-input label="ApiKey" placeholder="请输入Api-Key" v-model="model.apiKey" />
      </div>
      <div class="col-md-4 pl-md-1 text-left">
        <base-input label="BaseUrl" placeholder="请输入Base-Url" v-model="model.baseUrl" />
      </div>
      <div class="col-md-4 pl-md-1 text-left">
        <base-input label="ModelName" placeholder="请输入模型名称" v-model="model.modelName" />
      </div>
    </div>

    <br />

    <div class="row">
      <div class="col-lg-12 col-md-12">
        <card type="tasks">
          <template slot="header">
            <h3 class="title d-inline">评测指标</h3>
            <p class="card-category d-inline">请选择需要的评测指标</p>
          </template>
          <div class="table-full-width table-responsive">
            <ObservationMetricsList v-model="model.measurementMetrics"></ObservationMetricsList>
          </div>
        </card>
      </div>
    </div>

    <div class="row">
      <div class="col-md-6 text-left">
        <label class="form-label">评测模式</label>
        <div>
          <base-radio v-model="model.evaluationMode" name="auto">自动审核</base-radio>
          <base-radio v-model="model.evaluationMode" name="manual">人工审核</base-radio>
          <base-radio v-model="model.evaluationMode" name="hybrid">混合审核</base-radio>
        </div>
      </div>
      <div class="col-md-6 text-left">
        <label class="form-label">变形方式</label>
        <div>
          <base-checkbox v-for="(label, key) in transformOptions" 
            :key="key" 
            :checked="isChecked(key)" 
            @input="updateChecked(key, $event)">
            {{ label }}
          </base-checkbox>
        </div>
      </div>
    </div>

    <br /><br />

    <div class="row">
      <div class="col-md-6 text-left">
        <base-input label="最大 Token 数" placeholder="请输入最大 Token 数" v-model="model.maxToken" />
      </div>
      <div class="col-md-6 text-left">
        <base-input label="评测问题数量" placeholder="请输入评测问题的数量" v-model="model.questionNumber" />
      </div>
    </div>

    <template slot="footer">
      <div class="text-right col-lg-12">
        <base-button type="success" fill @click="submitTask">提交评测</base-button>
      </div>
    </template>
  </card>
</template>

<script>
import { Card, BaseInput } from "@/components/index";
import BaseButton from "@/components/BaseButton";
import ObservationMetricsList from "../../components/Dashboard/ObservationMetricsList";
import request from "../../request.js"; // 导入封装的请求方法
import { Message } from 'element-ui';
import router from "../../router";
export default {
  data() {
    return {
      model: {
        apiKey: "",
        baseUrl: "",
        modelName: "",
        measurementMetrics: [],
        metricMapping: {
          "核心功能准确性": 1,
          "内容安全性评估": 2,
          "隐私保护合规性": 3,
          "公平性与包容性检测": 4,
          "信息真实性验证": 5,
          "响应效率与资源消耗": 6,
          "抗干扰稳定性测试": 7,
        },
        evaluationMode: "auto",
        transformMethod: [],
        maxToken: "",
        questionNumber: "",
      },
      transformOptions: {
        1: "不采用变形",
        2: "语义改写（同义替换）",
        3: "选项调换（适用于选择题）",
        4: "提问方式改变（如将选择题变成简答题）",
        5: "题干扩展（增加背景信息）",
        6: "题目拆解（将复杂题拆分成多个小题）",
      },
    };
  },
  methods: {
    // 判断当前选项是否已选中
    isChecked(value) {
      return this.model.transformMethod.includes(value);
    },

    // 更新选中状态
    updateChecked(value, isChecked) {
      if (isChecked) {
        if (!this.model.transformMethod.includes(value)) {
          this.model.transformMethod.push(value);
        }
      } else {
        this.model.transformMethod = this.model.transformMethod.filter((item) => item !== value);
      }
    },

    // 校验是否有空值
    validateForm() {
      const { apiKey, baseUrl, modelName, measurementMetrics, maxToken, questionNumber } = this.model;
      
      if (!apiKey.trim()) return "ApiKey 不能为空";
      if (!baseUrl.trim()) return "BaseUrl 不能为空";
      if (!modelName.trim()) return "ModelName 不能为空";
      if (measurementMetrics.length === 0) return "请至少选择一个评测指标";
      if (!maxToken.trim()) return "最大 Token 数不能为空";
      if (!questionNumber.trim()) return "评测问题数量不能为空";
      
      return null; // 校验通过
    },

    // 提交任务
    async submitTask() {
      const errorMessage = this.validateForm();
      if (errorMessage) {
        Message.error(errorMessage);
        return;
      }

      try {
        const transformedMetrics = this.model.measurementMetrics
      .map(name => this.model.metricMapping[name])
      .filter(id => id !== undefined);  // 避免 undefined 进入数组
        const payload = {
          ...this.model,
          measurementMetrics: transformedMetrics, // 发送的是 ID 数组
        };
        const response = await request.post("/task/add", payload);
        if (response.code === 0) {
          Message.success("任务提交成功！");
          router.push("/notifications");
        } else {
          Message.error(response.message || "任务提交失败！");
        }
      } catch (error) {
        console.error("请求出错:", error)
        Message.error("请求失败，请稍后重试！");
      }
    },
  },
  components: {
    Card,
    BaseInput,
    BaseButton,
    ObservationMetricsList,
  },
};
</script>

<style>
.form-label {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  display: block;
}
</style>
